package com.wiener.chamilo.engine.services;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wiener.chamilo.engine.beans.Alumno;
import com.wiener.chamilo.engine.beans.Curso;
import com.wiener.chamilo.engine.beans.Seccion;
import com.wiener.chamilo.engine.commons.Constants;

@Service("integrationServices")
public class IntegrationServicesImpl implements IntegrationServices {

	// private File inputFile;
	private List<String> fileLinesUsers;
	private List<String> fileLinesCursos;
	private List<String> fileLinesSessiones;
	private List<Alumno> usuarios;
	private List<Curso> cursos;
	private List<Seccion> secciones;
	private boolean isDocente;

	@Autowired
	private LogTransactionService logTransactionService;

	private List<Alumno> getListUserToProcess(final List<String> fileLinesUsers)
			throws Exception {
		String[] objectoAlumno = null;
		Alumno alumno = null;

		usuarios = new ArrayList<Alumno>();
		for (String line : fileLinesUsers) {
			alumno = new Alumno();
			objectoAlumno = line.split(";");
			if (objectoAlumno.length > 0 && objectoAlumno.length <= 12
					&& objectoAlumno.length != 1) {

				if ("FIRSTNAME".equals(objectoAlumno[0])) {
					continue;
				}

				alumno = new Alumno();
				alumno.setSecretKey(Constants.CHAMILO_SERVER_UNO_SECRET_KEY);
				alumno.setFirstname(objectoAlumno[0]);
				alumno.setLastname(objectoAlumno[1]);
				alumno.setStatus(Integer.parseInt(objectoAlumno[2]));
				alumno.setEmail(objectoAlumno[3]);
				alumno.setLoginname(objectoAlumno[4]);
				alumno.setPassword(objectoAlumno[5]);
				alumno.setOriginal_user_id_name(objectoAlumno[6]);
				alumno.setOriginal_user_id_value(objectoAlumno[7]);
				alumno.setLanguage(objectoAlumno[8]);
				alumno.setPhone(objectoAlumno[9]);
				alumno.setExpiration_date(objectoAlumno[10]);
				if (!isDocente) {
					alumno.setUrl(objectoAlumno[11]);
				}

				alumno.setVisibility(0);

				usuarios.add(alumno);
			}
		}
		return usuarios;
	}

	private void moveFiletoBackDir(File inputFile) throws Exception {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		String fecha = "" + dateFormat.format(cal.getTime());
		File directorio = new File(Constants.CHAMILO_SERVER_DIR_BK + fecha);
		directorio.mkdir();
		FileUtils.moveFileToDirectory(inputFile, directorio, Boolean.TRUE);
	}

	private List<Curso> getListCursosToProcess(
			final List<String> fileLinesCursos) {
		String[] objectoCurso = null;
		Curso curso = null;

		cursos = new ArrayList<Curso>();
		for (String line : fileLinesCursos) {
			curso = new Curso();
			objectoCurso = line.split(";");
			if (objectoCurso.length > 0 && objectoCurso.length <= 12
					&& objectoCurso.length != 1) {

				if ("TITLE".equals(objectoCurso[0])) {
					continue;
				}

				curso = new Curso();
				curso.setSecretKey(Constants.CHAMILO_SERVER_UNO_SECRET_KEY);
				curso.setTitle(objectoCurso[0]);
				curso.setCategoryCode(objectoCurso[1]);
				curso.setWantedCode(objectoCurso[2]);
				curso.setTutorName(objectoCurso[3]);
				curso.setCourseAdminUserIdFieldName(objectoCurso[4]);
				curso.setCourseAdminUserIdValue(objectoCurso[5]);
				curso.setLanguage(objectoCurso[6]);
				curso.setCourseIdFieldName(objectoCurso[7]);
				curso.setCourseIdValue(objectoCurso[8]);

				cursos.add(curso);
			}
		}
		return cursos;

	}

	private void processAlumnoDocenteInformation(File inputFile)
			throws Exception {
		int counts = 0;
		if ("docente.txt".equals(inputFile.getName())) {
			isDocente = Boolean.TRUE;
		}
		// inputFile = new File(Constants.CHAMILO_SERVER_DIR);
		fileLinesUsers = FileUtils.readLines(inputFile);
		this.usuarios = getListUserToProcess(fileLinesUsers);
		for (Alumno alumno : this.usuarios) {
			(new Thread(new UserServiceImpl(alumno))).start();
			counts++;
			if (counts % 10 == 0) {
				Thread.sleep(10000);
			}
		}
	}

	private void processCousesInformation(File inputFile) throws Exception {
		int counts = 0;

		fileLinesCursos = FileUtils.readLines(inputFile);
		this.cursos = getListCursosToProcess(fileLinesCursos);
		for (Curso curso : this.cursos) {
			(new Thread(new CursoServiceImpl(curso))).start();
			counts++;
			if (counts % 10 == 0) {
				Thread.sleep(10000);
			}
		}

	}

	public synchronized void executeProcess() {
		System.out.println("executeProcess");

		try {
			File[] faFiles = new File(Constants.CHAMILO_SERVER_DIR).listFiles();
			for (File inputFile : faFiles) {

				if ("docente.txt".equals(inputFile.getName())
						|| "alumno.txt".equals(inputFile.getName())) {
					isDocente = Boolean.TRUE;
					processAlumnoDocenteInformation(inputFile);
				}
				if ("curso.txt".equals(inputFile.getName())) {
					processCousesInformation(inputFile);
				}
				if ("seccion.txt".equals(inputFile.getName())) {
					processSessionInformation(inputFile);
				}

				moveFiletoBackDir(inputFile);
			}

			System.out.println("executeProcess");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void processSessionInformation(File inputFile) throws Exception {
		// TODO Auto-generated method stub
		int counts = 0;
		fileLinesSessiones = FileUtils.readLines(inputFile);
		this.secciones = getListSeccionesToProcess(fileLinesSessiones);
		for (Seccion seccion : this.secciones) {
			(new Thread(new SessionServiceImpl(seccion))).start();
			counts++;
			if (counts % 10 == 0) {
				Thread.sleep(10000);
			}
		}

	}

	private List<Seccion> getListSeccionesToProcess(
			List<String> fileLinesSessiones2) {
		// TODO Auto-generated method stub

		String[] objectoSeccion = null;
		Seccion seccion = null;

		secciones = new ArrayList<Seccion>();
		for (String line : fileLinesSessiones) {
			seccion = new Seccion();
			objectoSeccion = line.split(";");
			if (objectoSeccion.length > 0 && objectoSeccion.length <= 14
					&& objectoSeccion.length != 1) {

				if ("NAME".equals(objectoSeccion[0])) {
					continue;
				}

				seccion = new Seccion();
				seccion.setSecretKey(Constants.CHAMILO_SERVER_UNO_SECRET_KEY);
				seccion.setName(objectoSeccion[0]);
				seccion.setStartDate(objectoSeccion[1] + "-"
						+ objectoSeccion[2] + "-" + objectoSeccion[3]);
				seccion.setEndDate(objectoSeccion[4] + "-" + objectoSeccion[5]
						+ "-" + objectoSeccion[6]);
				if (!"".equals(objectoSeccion[7].trim())) {
					seccion.setNbDaysAccessBefore(Integer.parseInt(objectoSeccion[7]));
				}
				if (!"".equals(objectoSeccion[8].trim())) {
					seccion.setNbDaysAccessAfter(Integer
							.parseInt(objectoSeccion[8]));
				}						
				if (!"".equals(objectoSeccion[9].trim())) {
					seccion.setNolimit(Integer.parseInt(objectoSeccion[9]));	
				}
				
				seccion.setUserIdFieldName(objectoSeccion[10]);
				seccion.setUserIdValue(objectoSeccion[11]);
				seccion.setSessionIdFieldName(objectoSeccion[12]);
				seccion.setSessionIdValue(objectoSeccion[13]);

				secciones.add(seccion);
			}
		}
		return secciones;
	}

}
